import axios from 'axios'
import { getToken } from '@/utils/auth'
import config from '@/utils/config'

const mimeMap = {
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  zip: 'application/zip',
  json: 'application/json'
}

/**
 * 批量下载 两个参数 只传url不许要进度条. 如果传递that 可以配带进度条
 * 调用方法1: downloadOpenLoading  显示进度条
 * 调用方法2: downloadProgress     刷新进度
 * 调用方法3: downloadCloseLoading 关闭进度条(遮盖层)
 * @param url 下载url
 * @param that 调用给本方法页面的 this  downLoadZip('url/....', this)
 */
export function downLoadZip(url, that) {
  console.log(config.baseURL)
  // 进度条值
  var percentage = 1
  // 打开遮盖层
  if (that !== undefined && that !== null) {
    that.msgInfo(that.$t('正在准备,请稍后!'))
    that.downloadOpenLoading()
    // 进度值开始前给0
    that.downloadProgress(percentage)
  }
  // 针对大文件.设置一个假进度条, 99%之前都是假的
  var JDT = setInterval(() => {
    if (percentage < 99 && that !== undefined) {
      // 每次随机加数字0-5
      percentage += (Math.floor(Math.random() * 5) + 1)
      // 前台显示百分比
      that.downloadProgress(percentage >= 99 ? 99 : percentage)
    }
  }, 3500)
  axios({
    method: 'get',
    url: config.baseURL + url,
    responseType: 'blob',
    headers: { 'Authorization': 'Bearer ' + getToken() },
    // 进度的事件
    onDownloadProgress: progressEvent => {
      if (progressEvent.lengthComputable && that !== undefined && that !== null) {
        var tempPercentage = Math.round(progressEvent.loaded / progressEvent.total * 100)
        clearInterval(JDT)
        if (tempPercentage >= percentage) {
          that.downloadProgress(tempPercentage)
        }
      }
    }
  }).then(res => {
    // 关闭遮盖层
    if (that !== undefined && that !== null) {
      setTimeout(() => {
        that.downloadCloseLoading()
      }, 1500)
    }
    try {
      resolveBlob(res, mimeMap.zip)
    } catch (e) {
      // console.log(e)
      setTimeout(() => {
        that.downloadCloseLoading()
      }, 1500)
    }
  })
}

// post请求
export function downLoadFilePost(str, params) {
  var url = config.baseURL + str
  axios({
    method: 'post',
    url: url,
    data: params,
    responseType: 'blob',
    headers: { 'Authorization': 'Bearer ' + getToken() }
  }).then(res => {
    resolveBlob(res, mimeMap.zip)
  })
}

/**
 *
 * 下载文件 两个参数 只传url不许要进度条. 如果传递that 可以配带进度条
 *
 * 用法: 父页面上需要以下几个方法 在页面v-loading="loading" 后面加上
 * :element-loading-text="loadingText"
 *
 * 调用方法1: downloadOpenLoading             显示进度条
 * 调用方法2: downloadProgress(percentage)    刷新进度
 * 调用方法3: downloadCloseLoading            关闭进度条(遮盖层)
 * @param downUrl 下载url
 * @param that 调用给本方法页面的 this  downLoadZip('url/....', this)
 */
export function downLoadFile(downUrl, that) {
  // 进度条值
  var percentage = 0
  // 打开遮盖层
  if (that !== undefined && that !== null) {
    that.downloadOpenLoading()
    // 进度值开始前给0
    that.downloadProgress(percentage)
  }
  axios({
    method: 'get',
    url: config.baseURL + downUrl,
    responseType: 'blob',
    headers: { 'Authorization': 'Bearer ' + getToken() },
    // 进度的事件
    onDownloadProgress: progressEvent => {
      if (progressEvent.lengthComputable && that !== undefined && that !== null) {
        percentage = Math.round(progressEvent.loaded / progressEvent.total * 100)
        that.downloadProgress(percentage)
      }
    }
  }).then(res => {
    try {
      resolveBlob(res, mimeMap.zip)
    } catch (e) {
      // console.log(e)
    }
    if (that) {
      that.downloadCloseLoading()
    }
  })
}

/**
 * 下载方式不跳转
 * @param param if: param为url, else: param为Id
 */
export function downLoadFileOpen(param) {
  // console.log(param)
  if (param.indexOf('/') !== -1) {
    if (param.indexOf('?') === -1) {
      param = param + '?Authorization=' + getToken()
    } else {
      param = param + '&Authorization=' + getToken()
    }
    // 自定义url下载方式
    window.open(config.baseURL + param, '_self')
  } else {
    // 默认下载方法
    window.open(config.baseURL + '/file/fileBase/common/download?id=' + param + '&Authorization=' + getToken(), '_self')
  }
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlob(res, mimeType) {
  const aLink = document.createElement('a')
  var blob = new Blob([res.data], { type: mimeType })
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  var pragma = decodeURI(res.headers['pragma'])
  var fileName = ''
  if (pragma !== undefined && pragma !== 'undefined' && pragma !== 'no-cache') {
    fileName = pragma.replaceAll('+', ' ')
  } else {
    var contentDisposition = decodeURI(res.headers['content-disposition'])
    var result = patt.exec(contentDisposition)
    if (result === null) {
      result = ['', 'download']
    }
    fileName = result[1]
  }
  fileName = fileName.replace(/\"/g, '')
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName === 'download' ? 'download.zip' : fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}

// 批量下载表单配置使用
const baseUrl = process.env.VUE_APP_BASE_API
export function downLoadZipOnl(url, that) {
  console.log(baseUrl)
  // 进度条值
  var percentage = 1
  // 打开遮盖层
  if (that !== undefined && that !== null) {
    that.msgInfo(that.$t('正在准备,请稍后!'))
    that.downloadOpenLoading()
    // 进度值开始前给0
    that.downloadProgress(percentage)
  }
  // 针对大文件.设置一个假进度条, 99%之前都是假的
  var JDT = setInterval(() => {
    if (percentage < 99 && that !== undefined) {
      // 每次随机加数字0-5
      percentage += (Math.floor(Math.random() * 5) + 1)
      // 前台显示百分比
      that.downloadProgress(percentage >= 99 ? 99 : percentage)
    }
  }, 3500)
  axios({
    method: 'get',
    url: baseUrl + url,
    responseType: 'blob',
    headers: { 'Authorization': 'Bearer ' + getToken() },
    // 进度的事件
    onDownloadProgress: progressEvent => {
      if (progressEvent.lengthComputable && that !== undefined && that !== null) {
        var tempPercentage = Math.round(progressEvent.loaded / progressEvent.total * 100)
        clearInterval(JDT)
        if (tempPercentage >= percentage) {
          that.downloadProgress(tempPercentage)
        }
      }
    }
  }).then(res => {
    // 关闭遮盖层
    if (that !== undefined && that !== null) {
      setTimeout(() => {
        that.downloadCloseLoading()
      }, 1500)
    }
    try {
      console.log(res, 'resres')
      if (res.data && res.data.type.includes('json')) {
        resolveBlob(res, mimeMap.json)
      } else {
        resolveBlob(res, mimeMap.zip)
      }
    } catch (e) {
      // console.log(e)
      setTimeout(() => {
        that.downloadCloseLoading()
      }, 1500)
    }
  })
}
